package com.killer.service;

import com.killer.dao.OrderMapper;
import com.killer.pojo.Order;
import com.killer.pojo.Seckill;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

@Service
public class OrderService {

    @Autowired
    private SeckillService seckillService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 根据秒杀生成订单
     * @param seckillId
     */
    public void createOrder(Long seckillId)  {
        //根据秒杀id查询秒杀活动详情
        Seckill seckill = seckillService.findById(seckillId);
        if (seckill == null) {
            return;
        }
        System.out.println("开始生成订单......");
        //创建订单
        Order order=new Order();
        order.setProductId(seckill.getId());
        order.setStatus(0);
        order.setSeckillId(seckillId);
        orderMapper.insert(order);
        //发送一条延迟消息用于删除过期未支付定点
        Message message =new GenericMessage(order.getId());
        //指定延迟时间  level=4，为30秒
        rocketMQTemplate.syncSend("order_check", message, 3000, 4);

    }

    public void deleteDueOrder(Long orderId) {
        //查看该订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return;
        }
        if (order.getStatus() == 1) {
            return;
        }
        System.out.println("订单id:"+orderId+"因为过期未支付而删除");
        Boolean result = redisTemplate.opsForValue().setIfAbsent("seckill_lock_" + order.getSeckillId(), "1", 30000, TimeUnit.SECONDS);
        if (result) {
            System.out.println(Thread.currentThread()+"获取到分布式锁执行恢复库存操作");
            try {
                order.setStatus(-1);
                orderMapper.updateById(order);
                //恢复库存
                seckillService.recoverStorage(order.getSeckillId());
                redisTemplate.opsForValue().increment("seckill_" + order.getSeckillId());
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                //业务完成,释放锁
                redisTemplate.delete("seckill_lock_" + order.getSeckillId());
            }
        }else{
            System.out.println(Thread.currentThread()+"线程没法获取到分布式锁执行恢复库存操作");
        }


    }
}
